package com.tongserver.huanxin.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tongserver.huanxin.entity.Myentity;
import com.tongserver.huanxin.entity.SubEntity;

import net.sf.json.JSONObject;

public class ChartDemoServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6120231785586005419L;
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 设置编码utf8
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 获取访问路径
		String url = request.getRequestURI();
		// 解析访问路径
		String action = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
		SubEntity subEntity;
		JSONObject obj;
		Random random = new Random();
		List<SubEntity> rows = new ArrayList<SubEntity>();
		PrintWriter out = response.getWriter();
		// 测试功能
		if (action.equals("/day")) {
			for(int i=0;i<30;i++){
				subEntity = new SubEntity(2*random.nextInt(100), 3*random.nextInt(100), (i+1)+"");
				rows.add(subEntity);
			}
			Myentity myentity = new Myentity(5,rows);
			//JSONArray json = new JSONArray();
			//json.add(myentity);
			obj = JSONObject.fromObject(myentity);
			System.out.println(obj.toString());
			out.write(obj.toString());
			out.close();
		}else if (action.equals("/week")) {
			for(int i=0;i<7;i++){
				subEntity = new SubEntity(2*random.nextInt(100), 3*random.nextInt(100), (i+1)+"");
				rows.add(subEntity);
			}
			Myentity myentity = new Myentity(5,rows);
			obj = JSONObject.fromObject(myentity);
			System.out.println(obj.toString());
			out.write(obj.toString());
		}else if (action.equals("/month")) {
			for(int i=0;i<12;i++){
				subEntity = new SubEntity(2*random.nextInt(100), 3*random.nextInt(100), (i+1)+"");
				rows.add(subEntity);
			}
			Myentity myentity = new Myentity(5,rows);
			obj = JSONObject.fromObject(myentity);
			System.out.println(obj.toString());
			out.write(obj.toString());
		}
	}
}
